/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package avl.sv.shared.sources;

import avl.sv.shared.ImageID;
import avl.sv.shared.SlideReference;
import avl.tiff.BufferingStatus;
import avl.tiff.TiffDirectory;
import avl.tiff.TiffDirectoryBuffer;
import avl.tiff.TiffFile;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author benbryan
 */
public class SlideSourceFile extends SlideSource {

    private final ArrayList<TiffDirectory> tds;
    
    public SlideSourceFile(File imageFile) throws IOException {
        super(new SlideReference(null, imageFile.getName(), ImageID.get(imageFile)));
        tds = TiffFile.getTiffDirectories(imageFile);
        gatherDirs();
    }

    private void gatherDirs() {
        for (int i = 0; i < tds.size(); i++) {
            TiffDirectory td = tds.get(i);
            Properties p = td.getProperties();
            TiffDirectoryBuffer tdb = new TiffDirectoryBuffer(p);
            byte tables[] = td.getJpegTables();
            if (tables != null) {
                try {
                    tdb.setupDecoder(tables);
                } catch (IOException ex) {
                    Logger.getLogger(SlideSourceFile.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            getTiffDirectoryBuffers().add(tdb);
        }
        parseDBuff();
    }

    @Override
    protected BufferedImage downloadTile(TiffDirectoryBuffer dir, int i, int j)  {
        BufferedImage img = null;
        try {
            byte b[];
            int dirIdx = getTiffDirectoryBuffers().indexOf(dir);
            b = tds.get(dirIdx).getTileAsByteArray(i, j);
            if (b != null) {
                img = dir.setTile(i, j, b);
                dir.setTileFechingStatus(i, j, BufferingStatus.BUFFERED);
            } else {
                dir.setTileFechingStatus(i, j, BufferingStatus.NOT_BUFFERED);
            }
            decrementAndGetActiveDownloadCount();
            startBuffering();
        } catch (IOException ex) {
            Logger.getLogger(SlideSourceFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        return img;
    }
}
